package com.ebupt.migu.ksms.utils;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class HTTPUtil {

    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 10000;
    // 线程安全的
    private static CloseableHttpClient httpClient;

    static {
        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();
        connMgr.setMaxTotal(500);
        connMgr.setDefaultMaxPerRoute(10);

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置链接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        requestConfig = configBuilder.build();
        httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
    }

    /**
     * 单线程下发
     *
     * @param apiUrl
     * @param json
     * @return
     */
    public String doPostSingleThread(String apiUrl, String json) {
        log.info("请求报文:{}", json);
        try {
            HttpPost httpPost = new HttpPost(apiUrl);
            CloseableHttpResponse response = null;
            httpPost.setConfig(requestConfig);
            // 防止中文乱码
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            if (null == response) {
                throw new RuntimeException("response 对象为空");
            }
            HttpEntity entity = response.getEntity();
            String httpStr = EntityUtils.toString(entity, "UTF-8");
            if (null != response) {
                EntityUtils.consume(response.getEntity());
            }
            log.info("发送短信结果返回：{}", httpStr);
            return httpStr;
        } catch (IOException e) {
            log.error("发送 POST 请求时出现错误：{}", e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}